package com.soft.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.util.DigestUtils;
import com.soft.entity.Employee; // 假设Employee实体存在，如果没有，需要创建
import com.soft.service.EmployeeService;

import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;


//员工注册（密码MD5加密后存储）

    @PostMapping("/registeremployee")
    public Map<String, Object> registerEmployee(
            @RequestParam String employeePassword,
            @RequestParam Long storeId) {
        Map<String, Object> res = new HashMap<>();
        try {
            String encryptedPwd = DigestUtils.md5DigestAsHex(employeePassword.getBytes());

            Long employeeId = employeeService.registerEmployee(encryptedPwd, storeId);
            if (employeeId != null) {
                res.put("state", "success");
                res.put("message", "注册成功");
                res.put("employeeId", employeeId);
            } else {
                res.put("state", "fail");
                res.put("message", "注册失败");
            }
        } catch (Exception e) {
            res.put("state", "fail");
            res.put("message", "注册异常");
        }
        return res;
    }


     // 员工登录（输入密码MD5加密后校验）

    @GetMapping("/login")
    public Map<String, Object> login(
            @RequestParam Long employeeId,
            @RequestParam String employeePassword) {
        Map<String, Object> res = new HashMap<>();

        // 登录时对输入密码进行 MD5 加密再比对
        String encryptedPwd = DigestUtils.md5DigestAsHex(employeePassword.getBytes());

        boolean success = employeeService.loginEmployee(employeeId, encryptedPwd);
        res.put("state", success ? "success" : "fail");
        res.put("message", success ? "登录成功" : "员工ID或密码错误");
        return res;
    }

    /**
     * 根据员工ID获取员工信息
     * @param employeeId 员工ID
     * @return 员工ID和门店ID，如果不存在返回null
     */
    @GetMapping("/getEmployeeById")
    public Map<String, Long> getEmployeeById(@RequestParam Long employeeId) {
        return employeeService.getEmployeeById(employeeId);
    }
}